<!-- 库存数量预警
少、正常、多（不同颜色区分）
显示建议库存区间
库存内容
铝合金、铜、玻璃、钢轨、钢材等等 -->

<!---
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Visualize Data</title>
        <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
            color: #333;
        }
        .form-container {
            background: white;
            padding: 10px;
            margin-top: 10px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            flex-wrap: wrap; /* Allows form fields to wrap */
            align-items: center; /* Align items vertically in the center */
            gap: 10px; /* Space between elements */
        }
        input, select, button {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            background-color: #5cb85c;
            color: white;
            border: none;
            cursor: pointer;
            padding: 5px 15px;
        }
        button:hover {
            background-color: #4cae4c;
        }
        label {
            margin-right: 5px; /* Space between label and input */
        }
    </style>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>


<body>
    <label for="modelSelect">选择模型:</label>
    <select id="modelSelect" onchange="toggleForms()">
        <option value="">Select a model</option>
        <option value="arima">ARIMA</option>
        <option value="lightgbm">LightGBM</option>
    </select>

    <div class="form-container" id="arimaForm" style="display: none;">
        <h3 align="center">ARIMA Model Parameters</h3>
        <div align="center">
            <input type="number" id="p" name="p" step="0.01" placeholder="Enter p value" required>
            <input type="number" id="d" name="d" step="0.01" placeholder="Enter d value" required>
            <input type="number" id="q" name="q" step="0.01" placeholder="Enter q value" required>
            <input type="number" id="steps" name="steps" step="1" placeholder="Enter number of steps" required>
            <button type="button" onclick="submitArimaParams()">Submit</button>
        </div>
    </div>

    <div class="form-container" id="lightGBMForm" style="display: none;">
        <h3 align="center">LightGBM Model Parameters</h3>
        <div align="center">
            <select id="boosting_type" name="boosting_type" placeholder="Boosting Type" required>
                <option value="">Select Boosting Type</option>
                <option value="gbdt">GBDT</option>
                <option value="dart">DART</option>
                <option value="goss">GOSS</option>
            </select>

            <input type="number" id="learning_rate" name="learning_rate" step="0.01" placeholder="Learning Rate" required>
            <input type="number" id="feature_fraction" name="feature_fraction" step="0.01" placeholder="Feature Fraction" required>
            <input type="number" id="bagging_fraction" name="bagging_fraction" step="0.01" placeholder="Bagging Fraction" required>
            <button type="button" onclick="submitLightGBMParams()">Submit</button>

        </div>
    </div>

    <button onclick="fetchData()">Show</button>
    <button onclick="clearData()">Clear</button>

    <div id="chart"></div>

    <script>
    function toggleForms() {
        var selection = document.getElementById("modelSelect").value;
        document.getElementById("arimaForm").style.display = (selection === "arima") ? "block" : "none";
        document.getElementById("lightGBMForm").style.display = (selection === "lightgbm") ? "block" : "none";
    }
    </script>

    <script>
    function submitArimaParams() {
        const p = document.getElementById('p').value;
        const d = document.getElementById('d').value;
        const q = document.getElementById('q').value;
        const steps = document.getElementById('steps').value;
        fetch('/run_arima', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ p: p, d: d, q: q, steps: steps })
        })
        .then(response => response.text())
        .then(data => {
            alert(data);
        })
        .catch(error => console.error('Error:', error));
    }

    function submitLightGBMParams() {
        const boosting_type = document.getElementById('boosting_type').value;
        const learning_rate = document.getElementById('learning_rate').value;
        const feature_fraction = document.getElementById('feature_fraction').value;
        const bagging_fraction = document.getElementById('bagging_fraction').value;
        fetch('/run_lightGBM', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({boosting_type: boosting_type, learning_rate: learning_rate, feature_fraction: feature_fraction, bagging_fraction: bagging_fraction})
        })
        .then(response => response.text())
        .then(data => alert(data))
        .catch(error => console.error('Error:', error));
    }
    </script>

    <script>
    function fetchData() {
        fetch('/process_data')
            .then(response => response.json())
            .then(data => {
                // 定义额外的布局设置
                const additionalLayout = {
                    xaxis: {
                        title: '日期（day）', // X轴标题
                    },
                    yaxis: {
                        title: '销售额（万元）', // Y轴标题
                    }
                };

                // 合并从后端接收的布局与额外布局设置
                const finalLayout = Object.assign({}, data.graph_json.layout, additionalLayout);

                Plotly.newPlot('chart', data.graph_json.data, finalLayout);
            })
            .catch(error => console.error('Error fetching data:', error));
    }
    </script>

    <script>
    function clearData() {
        fetch('/clear', {
            method: 'POST'
        })
        .then(response => response.text())
        .then(data => alert('Forecast data cleared!'))
        .catch(error => console.error('Error clearing data:', error));
    }
    </script>

</body>
</html> -->


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Inventory and Demand Visualization</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script> 
    <script src="https://cdn.jsdelivr.net/npm/echarts/map/js/china.js"></script>
    <script>
        // 在DOM加载完成后运行的函数
        window.onload = function() {
          // 获取按钮元素
          var popupButton = document.getElementById('popupButton');

          // 为按钮添加点击事件监听器
          popupButton.onclick = function() {
            // 显示alert弹窗
            alert('文件上传成功');
          };
        };
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
            color: #333;
        }
        #main {
            width: 100%;
            height: 800px; /* 增加高度 */
            margin: 0 auto;
        }

        .form-container {
            display: flex;        /* 使用Flexbox布局 */
            justify-content: space-around; /* 元素均匀分布 */
            align-items: center;  /* 垂直居中 */
            padding: 10px;
            margin-top: 10px;
            margin-bottom: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            flex-wrap: wrap; /* Allows form fields to wrap */
            gap: 10px; /* Space between elements */
        }

        select,input {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        button {
            background-color: #5cb85c;
            color: white;
            border: none;
            cursor: pointer;
            padding: 5px 15px;
        }
    </style>
</head>
<body>
    <h2 class = form-container>库存分配模块</h2>
    <div class="form-container">
                <!-- 文件选择下拉框 -->
        <div>
            <form id="dataForm">
                <label for="fileSelector">选择模型:</label>
                <select id="fileSelector" name="dataset">
                    <option value="1">EOQ</option>
                    <option value="2">MEIO</option>
                    <option value="3">DP</option>
                    <option value="4">LSTM</option>
                </select>
                <input type="submit" value="显示结果">
            </form>
        </div>

        <div>
            <form enctype="multipart/form-data">
            <label>上传历史数据(CSV):</label>
            <input type="file" name="file" id="fileInput" required>
            <button id="popupButton">上传文件</button>
            </form>
        </div>
    </div>
    <div class="form-container">
        <div id="main"></div>
    </div>

    <!-- <script>
        function showalert() {
            const fileInput = document.getElementById("fileInput");
            const file = fileInput.files[0]; // 获取选中的文件

            if (file) {
                alert(`上传的文件${file.name}\n大小为${file.size}`);
            } else {
                alert("未上传文件");
            }
        }
    </script> -->

    <script type="text/javascript">
        var chart = echarts.init(document.getElementById('main'));

        document.getElementById('dataForm').addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止表单默认提交行为
            var dataset = document.getElementById('fileSelector').value;
            fetchDataForChart(dataset);
        });

        function fetchDataForChart(dataset) {
            fetch(`/get_inventory_data`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `dataset=${dataset}`
            })
            .then(response => response.json())
            .then(data => {
                updateChart(data);
            })
            .catch(error => console.error('Error fetching data:', error));
        }

        function updateChart(data) {
            var data_ratio = data.map(function (item) {
                var color;
                if (item.ratio > 1) {
                    // 库存大于需求，使用绿色
                    var greenIntensity = Math.min(item.ratio, 2) - 1; // 计算绿色强度（1到2之间）
                    color = `rgba(0, 255, 0,  ${Math.max(greenIntensity, 0.5)})`; // 比值越大，颜色越深
                } else if (item.ratio === 1) {
                    color = 'rgba(255, 255, 0, 1)'; // 库存刚好满足需求，使用黄色
                } else {
                    var redIntensity = item.ratio; // 计算红色强度（0到1之间）
                    color = `rgba(255, 0, 0,  ${Math.max(redIntensity, 0.5)})`; // 比值越小，颜色越深
                }

                return {
                    name: item.name,
                    value: [item.longitude, item.latitude, item.inventory],  // 假设后端返回的数据包含经纬度
                    itemStyle: {
                        color: color,
                    },
                    symbolSize: item.demand / 50,
                };
            });

            var option = {
                title: {
                    // text: 'Inventory and Demand Distribution in China',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        var inventory = params.data.value[2];
                        var demand = data.find(d => d.name === params.name).demand;
                        var ratio = (inventory / demand).toFixed(2);
                        return params.name + '<br/>库存: ' + inventory + '<br/>需求: ' + demand + '<br/>库存/需求比: ' + ratio;
                    }
                },
                geo: {
                    map: 'china',
                    roam: true,
                    label: {
                        emphasis: {
                            show: false
                        }
                    },
                    itemStyle: {
                        normal: {
                            areaColor: '#dfe8f7',
                            borderColor: '#111'
                        },
                        emphasis: {
                            areaColor: '#c4d3ff'
                        }
                    }
                },
                series: [
                    {
                        name: 'Inventory vs Demand',
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        data: data_ratio,
                        itemStyle: {
                            normal: {
                                opacity: 0.8
                            }
                        }
                    }
                ]
            };

            chart.setOption(option);
        }
    </script>
</body>
</html>